import uuid
from typing import List

from fastapi import Depends, HTTPException, APIRouter
from sqlalchemy.orm import Session, joinedload
from ..database import SessionLocal, engine
from ..schemas import VoteCreate, VoteUpdate
from backend.app.routes.websockets import ConnectionManager
from .. import models, schemas
import redis

cm = ConnectionManager()
models.Base.metadata.create_all(bind=engine)
router = APIRouter()



def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
lockname = "test"
redis_client = redis.Redis(host='101.42.30.13', port=6379, password='')
locker_id = uuid.uuid4().hex


def _acquire():
    """尝试获取锁，如果获取成功返回 True"""
    return redis_client.set(lockname, locker_id, nx=True, ex=10) is not None


def _release():
    """释放锁"""
    locker_id = redis_client.get(lockname)
    if locker_id and locker_id.decode() == locker_id:
        redis_client.delete(lockname)
@router.post("/votes/", response_model=VoteCreate)
async def create_vote(vote: VoteCreate, db: Session = Depends(get_db)):
    db_vote = models.Vote(question=vote.question, question_type=vote.question_type)
    db.add(db_vote)
    db.commit()
    db.refresh(db_vote)
    # 创建选项
    for option in vote.options:
        db_option = models.VoteOption(vote_id=db_vote.id, content=option.content)
        db.add(db_option)
    db.commit()
    return db_vote
@router.get("/votes/", response_model=List[schemas.Vote])
async def read_votes(db: Session = Depends(get_db)):
    votes = db.query(models.Vote).options(joinedload(models.Vote.options)).all()
    return votes
@router.get("/votes/{id}", response_model=schemas.Vote)
async def read_vote(id: int, db: Session = Depends(get_db)):
    db_vote = db.query(models.Vote).filter(models.Vote.id == id).first()
    if db_vote is None:
        raise HTTPException(status_code=404, detail="Vote not found")
    # 加载关联的选项
    options = db.query(models.VoteOption).filter(models.VoteOption.vote_id == id).all()
    db_vote.options = options
    return db_vote


@router.post("/votes/{vote_id}/submit", response_model=schemas.Vote)
async def submit_vote(
        vote_id: int,
        request_data: schemas.UserVoteRequest,
        db: Session = Depends(get_db),
        ):

    # 查询投票是否存在
    vote = db.query(models.Vote).filter(models.Vote.id == vote_id).first()
    if not vote:
        raise HTTPException(status_code=404, detail="Vote not found")
    if _acquire():
        try:
            # 执行需要加锁的代码
            # 更新投票选项的票数
            option_id = request_data.options  # 单选值
            option = db.query(models.VoteOption).filter(
                models.VoteOption.id == option_id,
                models.VoteOption.vote_id == vote_id
            ).first()
            if not option:
                raise HTTPException(status_code=400, detail="Invalid option ID")
            option.vote_count += 1

            # 记录用户投票（假设有一个 UserVoteRecord 模型）
            user_vote_record = models.UserVoteRecord(
                vote_id=vote_id,
                option_ids=str([option_id])  # 存储为单一值
            )
            db.add(user_vote_record)

            # 提交更改到数据库
            db.commit()
            # 刷新投票对象以获取最新数据
            db.refresh(vote)
            return vote
        finally:
            _release()
    else:
        return {"error": "Failed to acquire lock"}
